package com.zlsy.thread.threadlocal;

import lombok.Data;

import java.util.Objects;

/**
 * @author zhouliang
 * @date 2020/7/12 17:51
 */
public class ThreadLocalNormalUsage07 {

    public static void main(String[] args) {
        new ThreadLocalNormalUsage07Service1().buildUserInfo();
    }

}

class ThreadLocalNormalUsage07Service1 {
    public void buildUserInfo() {
        ThreadLocalNormalUsage07User usage07User = new ThreadLocalNormalUsage07User();
        usage07User.setName("张三");
        UserContextHolder07.userThreadLocal.set(usage07User);

        new ThreadLocalNormalUsage07Service2().buildUserInfo();
    }
}

class ThreadLocalNormalUsage07Service2 {
    public void buildUserInfo() {
        ThreadLocalNormalUsage07User usage07User = UserContextHolder07.userThreadLocal.get();
        System.err.println(usage07User.getName() + " 将被干掉！");
        UserContextHolder07.userThreadLocal.remove();

        new ThreadLocalNormalUsage07Service3().buildUserInfo();
    }
}

class ThreadLocalNormalUsage07Service3 {
    public void buildUserInfo() {
        ThreadLocalNormalUsage07User usage07User = UserContextHolder07.userThreadLocal.get();
        System.out.println("我是: " + (Objects.nonNull(usage07User) ? usage07User.getName() : ""));
    }
}

@Data
class ThreadLocalNormalUsage07User {
    private String name;
}

class UserContextHolder07 {
    public static ThreadLocal<ThreadLocalNormalUsage07User> userThreadLocal = new ThreadLocal<>();
}